import { AnimationTask } from './animation.sjs';

const queryElement = (ownerInstance, classSelector) => {
  return ownerInstance.selectComponent(`.${classSelector}`);
};

let instance = null;
let mode = 'conflict';
let lock = false;

const sliderLeftAnim = new AnimationTask(0, 5000, 1);

const sliderTracLeftAnim = new AnimationTask(0, 5000, 1);

let moveableLen, sliderWidth, viewWidth;
let startX = 0;
let movePosition;
let currentSliderLeftMove = 0;

const observerMode = modeProps => {
  mode = modeProps;
};

const observerLock = lockProps => {
  // lock = lockProps;
  lock = false;
};

const observerLeftValue = (newValue, oldValue, ownerInstance) => {
  if (!instance) {
    instance = ownerInstance;
  }

  const moveableLen = getMoveableLen(ownerInstance);

  ownerInstance.eventChannel.on('sliderChange', res => {
    console.log(`🚀 ~ res:`, res);
    // if (checkEventInstanceId) {
    //   if (res.instanceId === instanceId) {
    //     const cssVal = mathFunc(valueStart + res.value * valueScale);
    //     textNode.setStyle(createStyle(ownerInstance, instanceId, cssVal));
    //   }
    // } else {
    //   const cssVal = mathFunc(valueStart + res.value * valueScale);
    //   textNode.setStyle(createStyle(ownerInstance, instanceId, cssVal));
    // }
  });

  if (!moveableLen) return;

  const value = Math.min(100, Math.max(0, newValue));
  const len = (value * moveableLen) / 100;

  currentSliderLeftMove = len;
  sliderLeftAnim.setImmediate(len);

  sliderLeftAnim.maxChangedValue = moveableLen;
  sliderTracLeftAnim.maxChangedValue = moveableLen;

  // 初始化动画参数
  if (!sliderLeftAnim.lastTime) {
    sliderLeftAnim.setImmediate(len);
    sliderTracLeftAnim.setImmediate(len);
  } else {
    // 变化超过 1% 时才触发动画更新
    if (Math.abs(sliderLeftAnim.value - len) >= moveableLen / 100) {
      sliderLeftAnim.startAnimation(len);
      sliderTracLeftAnim.startAnimation(len);
    }
  }
};

const getMoveableLen = ownerInstance => {
  if (moveableLen) return moveableLen;
  const container = queryElement(ownerInstance, 'container');
  const leftSlider = queryElement(ownerInstance, 'slider-left');
  if (!container || !leftSlider) return;
  const view = container.getBoundingClientRect();
  const leftView = leftSlider.getBoundingClientRect();
  sliderWidth = leftView.width;
  viewWidth = view.width;
  moveableLen = view.width - sliderWidth;
  return moveableLen;
};

const getCurrentPercent = (ownerInstance, value) => {
  if (!moveableLen) getMoveableLen(ownerInstance);

  return Math.max(0, Math.floor(((value ?? currentSliderLeftMove) / moveableLen) * 100));
};

const setSliderStyle = (ownerInstance, value, type) => {
  const leftSlider = queryElement(ownerInstance, 'slider-left');
  const leftSliderTrac = queryElement(ownerInstance, 'track_left');

  const move = Math.max(0, Math.min(moveableLen, value));

  currentSliderLeftMove = move;

  leftSlider.setStyle({
    left: `${move}px`,
  });

  leftSliderTrac.setStyle({
    width: `${move + sliderWidth}px`,
  });

  const positionValue = queryElement(ownerInstance, 'position');

  const percent = getCurrentPercent(ownerInstance, value);

  console.log(percent, 'setSlider');
  positionValue.setStyle({
    '--percent-content': `"${percent}%"`,
  });

  // 不是由拖动引起的，不触发change事件
  if (!movePosition) return;

  ownerInstance.triggerEvent('change', {
    value: percent,
  });
};

sliderLeftAnim.onUpdate = function(value) {
  setSliderStyle(instance, value, 'left');
};

const handleStart = (event, ownerInstance) => {
  if (lock) return;
  const { clientX } = event.touches[0];
  const { position } = event.currentTarget.dataset;
  // 没找到position？发生了异常
  if (!position || !['left'].includes(position)) return;

  movePosition = position;

  sliderLeftAnim.stopAnimation();
  sliderTracLeftAnim.stopAnimation();
  startX = clientX;
  ownerInstance.callMethod('onSlidering');
};

const handleMove = (event, ownerInstance) => {
  if (lock) return;
  const { clientX } = event.touches[0];
  if (!movePosition) return;
  // 使用offsetLeft代替left
  const left = currentSliderLeftMove;
  const diff = clientX - startX;

  sliderLeftAnim.setImmediate(left + diff);
  sliderTracLeftAnim.setImmediate(left + diff);
  startX = clientX;
};

const handleEnd = (event, ownerInstance) => {
  if (lock) return;
  const percent = getCurrentPercent(ownerInstance);
  ownerInstance.triggerEvent('changend', {
    value: {
      percent,
    },
  });

  movePosition = '';
  ownerInstance.callMethod('onSliderEnd');
};

let lastControl = '';
const controlChange = (newControl, oldControl, ownerInstance) => {
  if (newControl !== lastControl) {
    lastControl = newControl;
    if (newControl === 'stop') {
      // sliderAnim.stopAnimation();
    } else if (newControl === 'continue') {
    }
  }
};

module.exports = {
  handleStart,
  handleMove,
  handleEnd,
  controlChange,
  observerMode,
  observerLeftValue,
  observerLock,
};
